﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Windows.Forms;

namespace Components
{
    public class GridViewUtil
    {
        private static GridViewUtil _instance = null;

        public static GridViewUtil Entity
        {
            get
            {
                if (_instance == null)
                    return new GridViewUtil();
                return _instance;
            }
        }


        public DataTable GridToTable(DataGridView dv)
        {
            DataTable dt = new DataTable();
            DataColumn dc;
            for (int i = 0; i < dv.Columns.Count; i++)
            {
                dc = new DataColumn();
                dc.ColumnName = dv.Columns[i].HeaderText.ToString();
                dt.Columns.Add(dc);
            }
            for (int j = 0; j < dv.Rows.Count - 1; j++)
            {
                DataRow dr = dt.NewRow();
                for (int x = 0; x < dv.Columns.Count; x++)
                {
                    dr[x] = dv.Rows[j].Cells[x].Value;
                }
                dt.Rows.Add(dr);
            }
            return dt;
        }

        /// <summary>
        /// 得到列头的宽度
        /// </summary>
        /// <returns></returns>
        public int GetHeadWidth(string headText)
        {
            if (string.IsNullOrEmpty(headText)) return 0;
            int pix = headText.Length < 3 ? 33 : 26; //暂时不知道为什么两个字的时候空间会不够
            return headText.Length * pix;  //13 是字号 
        }
    }
}
